import { Component, OnInit, OnDestroy } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'

import { ComWindow } from '@shared/classes/ComWindowClass'
import { INewPageColumn } from '@shared/interfaces/common'
import { MerchantNewBaseComponent } from './base/base.component'
import { MerchantNewSystemComponent } from './system/system.component'
import { MerchantNewUserComponent } from './user/user.component'
import { MerchantStoreService } from './merchant-store.service'
import { MerchantService } from '../merchant.service'
import { PageService } from '@shared/services/page.service'
import { encryptPassword } from 'app/utils/helpers'
import { User } from '@shared/interfaces/user'
import { MerchantNewTradeComponent } from './trade/trade.component'
import { I18NService } from '@core'

@Component({
  selector: 'app-merchant-new',
  templateUrl: './new.component.html',
})
export class MerchantNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    public msg: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    private merchantStore: MerchantStoreService,
    private merchantService: MerchantService,
    private pageService: PageService,
    private i18n: I18NService,
  ) {}

  ngOnInit(): void {
    this.initColumns()
  }

  ngOnDestroy(): void {
    this.merchantStore.reset()
  }

  initColumns() {
    this.pages = [
      {
        component: new ComWindow(MerchantNewSystemComponent, { title: 'GENERAL.INFO.OTHER.SYSTEM_INFO' }),
      },
      {
        component: new ComWindow(MerchantNewBaseComponent, { title: 'GENERAL.INFO.OTHER.BASIC_CONFIG' }),
      },
      {
        component: new ComWindow(MerchantNewTradeComponent, { title: 'GENERAL.INFO.OTHER.TRADE_INFO' }),
      },
      {
        component: new ComWindow(MerchantNewUserComponent, { title: 'GENERAL.INFO.OTHER.USERS' }),
      },
    ]
  }

  submit(): void {
    const merchant = this.merchantStore.value
    // encrypt user password
    merchant.users.forEach((user: User) => {
      user.password = encryptPassword(user.password)
    })
    const authPassword = merchant.merchant.common.tradeInfo.authPassword
    merchant.merchant.common.tradeInfo.authPassword = encryptPassword(authPassword)
    delete merchant.merchant.common.tradeInfo.authPasswordCF
    this.merchantService.create(merchant).subscribe(data => {
      this.pageService.triggerGuardAlive(false)
      this.merchantStore.reset()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
      this.router.navigate(['..'], { relativeTo: this.route })
    },
    err => {
      this.msg.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
